﻿bkLib.onDomLoaded(function my_func() {
    //var currentNicEditContent = nicEditors.findEditor('FinishedText').getContent(),
    //$("#nicEditId").autocomplete({
    //    $(".nicEdit-main").autocomplete({
    $("#MainContent_TextBox1").autocomplete({
        source: function (request, response) {
            $.getJSON("AutoComplete.ashx", {
                term: extractLast(request.term),
                //term: extractLast(nicEditors.findEditor('FinishedText').getContent()),
                gender: function () {
                    return $("#<%=GenreHiddenTextArea.ClientID%>").val();
                }
            }, response);
        },
        position: { my: "right top", at: "right bottom" },
        search: function () {
            // custom minLength  
            var term = extractLast(nicEditors.findEditor('FinishedText').getContent());
            if (term.length < 1) {
                return false;
            }
        },
        focus: function () {
            // prevent value inserted on focus 
            return false;
        },
        select: function (event, ui) {

            // split words
            //debugger;
            //var terms = splitOnSpace(removeHtmlTags(this.value));
            //alert("this.value: " + this.value);
            var terms = nicEditors.findEditor('FinishedText').getContent();
            var foundWordIndex = 0; //terms.lastIndexOf(termsLastWord);
            var termsLastWord = extractLast(terms);

            var termsBeginning = terms.substring(0, foundWordIndex);
            var termsEnding = terms.substring(foundWordIndex + termsLastWord.length, terms.length);

            termsLastWord = ui.item.TextAbreviere;

            // if (modelTextOriginal != "") updateModel(termsLastWord);

            termsLastWord = getTextFormat(termsLastWord);

            terms = termsBeginning + termsLastWord + termsEnding;

            nicEditors.findEditor('FinishedText').setContent(terms);

            tempString = terms;


            function getTextFormat(tempString4) {
                tempString4 = isTextBold(ui.item.Bold, true) + isTextItalic(ui.item.Italic, true) + getTextSize(ui.item.MarimeText, true)
                            + tempString4// + '&nbsp;'
                            + isTextBold(ui.item.Bold, false) + isTextItalic(ui.item.Italic, false) + getTextSize(ui.item.MarimeText, false);

                return tempString4;
            }



            function updateModel(generatorText) {
                modelTextResult = "";
                modelTextRed = "<font color='red'>";
                generatorTextTemp = generatorText.split(" ");
                generatorTextTemp2 = generatorText.split(" ");

                // generatorTextTemp.split(" ");
                //          alert("model active/has text");
                var s1, s2;
                do {
                    lastWord = (generatorTextTemp.pop()).toString();
                    lastWordRepetitions = 0;

                    if (lastWord.length > 3) {
                        //              alert(lastWord.length);

                        for (i = 0; i < generatorTextTemp2.length - 1; i++) {
                            s1 = generatorTextTemp2[i].toLowerCase();

                            try {
                                //get rid of all the signs(except a few) and keep only the letters in the word
                                s1 = generatorTextTemp2[i].match(/[A-z]/g).toString();
                            } catch (ex) {
                            }

                            if (s1.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                                lastWordRepetitions++;
                            }
                        }

                        if (lastWordRepetitions > 0) {

                            modelText = modelTextOriginal;
                            modelTextTemp = modelText.split(" ");

                            for (i = 0; i < modelTextTemp.length; i++) {
                                s2 = modelTextTemp[i].toLowerCase();
                                try {
                                    //get rid of all the signs(except a few) and keep only the letters in the word
                                    s2 = modelTextTemp[i].match(/[A-z]/g).toString();
                                } catch (ex) {
                                }

                                if (s2.toLowerCase() == lastWord.toLowerCase().match(/[A-z]/g).toString()) {
                                    lastWordRepetitions--;
                                    if (lastWordRepetitions == 0) {
                                        //                         alert("color 'till u get here:" + modelTextTemp[i] + " " + modelTextTemp[i + 1]);

                                        modelTextTemp.splice(i + 1, 0, "</font><div id='imHere' style='position: relative; bottom: 100px'></div>");
                                        modelTextResult = modelTextRed + modelTextTemp.join(" ");

                                        document.getElementById("MainContent_DataList1_TextModelLabel_0").innerHTML = modelTextResult;
                                        document.getElementById('imHere').scrollIntoView(true);

                                        break;
                                    }
                                }
                            }
                        }
                    }

                } while (lastWord.length < 4);

            }

            return false;
        }
    })
                .data("autocomplete")._renderItem = function (ul, item) {
                    return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a>" + item.Abreviere + " : " + item.TextAbreviere + " - " + item.Specialitate + "</a>")
                        .appendTo(ul);
                };

    function split(val) {
        return val.split(/ \s*|\r\n|\r|\n/);
        //return val.split(" ");
    }

    function splitOnSpaceAndDot(val) {
        return val.split(/[\s.]+/);
    }

    function splitOnSpace(val) {
        return val.split(" ");
    }

    function splitOnEnter(val) {
        return val.split(/\r\n|\r|\n/);
    }

    function splitOnDot(val) {
        return val.split(".");
    }

    function extractLast(term) {
        //remove html tags
        var initialText = term;
        var lastCaracters = "";
        var lastWord = "";
        var wordsList = "";

        var i = initialText.length - 1;
        while (i >= 0) {

            if (initialText.charAt(i) == ">") {

                while (initialText.charAt(i) != "<" && i >= 0) {
                    lastCaracters = lastCaracters + initialText.charAt(i);
                    i--;
                }
                lastCaracters = lastCaracters + initialText.charAt(i);
                i--;

                while (initialText.charAt(i) != ">" && i >= 0) {
                    wordsList = wordsList + initialText.charAt(i);
                    i--;
                }
                if (wordsList.length != 0) {
                    for (var x = wordsList.length; x >= 0; x--) {
                        lastWord = lastWord + wordsList.charAt(x);
                    }
                    //foundWordIndex = i;
                    break;
                }

            } else {
                while (initialText.charAt(i) != ">" && i >= 0) {
                    wordsList = wordsList + initialText.charAt(i);
                    i--;
                }
                if (wordsList.length != 0) {
                    for (var x = wordsList.length; x >= 0; x--) {
                        lastWord = lastWord + wordsList.charAt(x);
                    }
                    //foundWordIndex = i;
                    break;
                }
            }
            //i--;
        }
        this.foundWordIndex = i;
        lastWord = lastWord.split(" ").pop();

        //alert("searching:" + lastWord);
        return lastWord;
    }

    function removeHtmlTags(text) {
        var x = $("<span>" + term + "</span>").text();
        x = splitOnSpaceAndDot(x).pop();
    }
});